﻿using System;
using System.Linq.Expressions;
using System.Web.Mvc;
using System.Web.Mvc.Html;

namespace Gama.Extension
{
    public static partial class HtmlHelperExtensions
    {
        public static RadioButtonBuilder<TModel> RadioButtonEx<TModel>(this HtmlHelper htmlHelper, Expression<Func<TModel, object>> expression)
        {
            return new RadioButtonBuilder<TModel>(htmlHelper, expression);
        }
    }

    public class RadioButtonBuilder<TModel> : HtmlInputElementBuilder<TModel>
    {
        private bool unselected = false;

        internal RadioButtonBuilder(HtmlHelper htmlHelper, Expression<Func<TModel, object>> expression)
            : base(htmlHelper, expression)
        {
        }

        protected override string BuildCore()
        {
            if (this.value == null)
            {
                this.value = expression.Compile()((TModel)htmlHelper.ViewData.Model);
            }

            bool selected = !this.unselected && Object.Equals(this.value, expression.Compile()((TModel)htmlHelper.ViewData.Model));

            string radioName = htmlHelper.BuildBindingPath(this.expression);
            var attributes = Helpers.BuildDictionaryFromProperties(this.htmlAttributes);

            if (!attributes.ContainsKey("id"))
            {
                attributes.Add("id", String.Format("{0}_{1}", radioName.Replace('.', '_'), this.value));
            }

            return this.htmlHelper.RadioButton(htmlHelper.BuildBindingPath(this.expression), this.value, selected, attributes).ToHtmlString();
        }

        public RadioButtonBuilder<TModel> Unselected()
        {
            this.unselected = true;

            return this;
        }
    }
}
